package com.tttshaoqi.controller;
import com.tttshaoqi.dto.UserDTO;
import com.tttshaoqi.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tttshaoqi
 * &#064;create 2025-07-30-19:44
 */
@RestController
@RequestMapping("security")
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("login")
    public String login(@RequestBody UserDTO userDTO){
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(userDTO.getUsername(), userDTO.getPassword());

        Authentication authenticate = authenticationManager.authenticate(token);

        if(authenticate.isAuthenticated()){
            Object principal = authenticate.getPrincipal();
            Map<String,Object> map = new HashMap<>();
            map.put("user",principal);
            String jwt = JwtUtil.createJWT("tttshaoqi",36000,map);
            return jwt;
        }
        return "";
    }
}
